package com.drinks.yiniang.ui.activity.community;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.viewpager.TabFragmentAdapter;
import com.drinks.yiniang.entity.community.UserCommunityNewsJson;
import com.drinks.yiniang.entity.event.CommunityFollowEvent;
import com.drinks.yiniang.entity.event.ShopCartEvent;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.activity.conversation.ServiceChatActivity;
import com.drinks.yiniang.ui.fragment.community.user.UCCommentsFragment;
import com.drinks.yiniang.ui.fragment.community.user.UCShareFragment;
import com.drinks.yiniang.ui.fragment.community.user.UCWishListFragment;
import com.drinks.yiniang.ui.widget.dialog.ShareDialog;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户(其他用户)社区动态
 *
 * @author han
 * @date 2019/09/10
 */
public class UserCommunityActivity extends BaseTranBarActivity implements OnNavgationBarClickListener, TabLayout.OnTabSelectedListener {

    //nav
    private NavigationBarLayout nav_bar_user_community;
    //头像
    private CircleImageView iv_uc_avatar;
    //消息
    private ImageView iv_uc_message;
    //关注数量
    private TextView tv_uc_follows_value;
    //粉丝数
    private TextView tv_uc_fans_value;
    //赞同数
    private TextView tv_uc_praise_value;
    //tab
    private TabLayout tab_user_community;
    //关注状态
    private Button btn_uc_follow;
    //vp
    private ViewPager vp_user_community;

    private UCShareFragment mUcShareFragment;
    private UCCommentsFragment mUcCommentsFragment;
    private UCWishListFragment mUcWishListFragment;

    private TabFragmentAdapter mTabFragmentAdapter;

    private List<BaseLazyFragment> mFragments;

    private String[] mTabs;

    private String mUserId;
    private String mUserNickName;
    //关注状态 0未关注 1已关注 2相互关注 3已屏蔽（可以点击取消屏蔽）
    private String mFollowStatus;

    @Override
    protected void initView() {
        nav_bar_user_community = findViewById(R.id.nav_bar_user_community);

        iv_uc_avatar = findViewById(R.id.iv_uc_avatar);
        iv_uc_message = findViewById(R.id.iv_uc_message);

        tv_uc_follows_value = findViewById(R.id.tv_uc_follows_value);
        tv_uc_fans_value = findViewById(R.id.tv_uc_fans_value);
        tv_uc_praise_value = findViewById(R.id.tv_uc_praise_value);

        btn_uc_follow = findViewById(R.id.btn_uc_follow);

        tab_user_community = findViewById(R.id.tab_user_community);

        vp_user_community = findViewById(R.id.vp_user_community);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mUserId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyUserId) : null;

        initTabAndAdapter();

        getUserCommunityData();
    }

    private void initTabAndAdapter() {
        mTabs = new String[]{getString(R.string.text_share), getString(R.string.text_do_comments), getString(R.string.text_wish_list)};

        mFragments = new ArrayList<>(mTabs.length);

        for (int i = 0; i < mTabs.length; i++) {
            tab_user_community.addTab(tab_user_community.newTab().setText(mTabs[i]));
        }

        mUcShareFragment = UCShareFragment.newInstance(mUserId);
        mUcCommentsFragment = UCCommentsFragment.newInstance(mUserId);
        mUcWishListFragment = UCWishListFragment.newInstance(mUserId);

        mFragments.add(mUcShareFragment);
        mFragments.add(mUcCommentsFragment);
        mFragments.add(mUcWishListFragment);

        //初始化viewpager数据
        mTabFragmentAdapter = new TabFragmentAdapter(getSupportFragmentManager(), mFragments, mTabs);

        vp_user_community.setOffscreenPageLimit(2);
        vp_user_community.setAdapter(mTabFragmentAdapter);
        tab_user_community.setupWithViewPager(vp_user_community);
    }

    @Override
    protected void initListener() {
        nav_bar_user_community.setOnNavgationBarClickListener(this);
        btn_uc_follow.setOnClickListener(this);
        iv_uc_message.setOnClickListener(this);
        tab_user_community.addOnTabSelectedListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_uc_follow://关注状态
                if(!ActivityUtils.isLogined(this, true)) {
                    return;
                }
                doFollow();
                break;
            case R.id.iv_uc_message://私聊
                if(!ActivityUtils.isLogined(this, true)) {
                    return;
                }
                Intent intent = new Intent(mContext, ServiceChatActivity.class);
                intent.putExtra(Constants.KeyUserId, mUserId);
                intent.putExtra(Constants.KeyTitle, mUserNickName);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_user_community;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        ShareDialog dialog = ShareDialog.newInstance();

        dialog.show(getSupportFragmentManager(), Constants.TAG_SHARE_DIALOG);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    //关注或取消关注
    private void doFollow() {
        if(StringUtils.isEmpty(mUserId)) {
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        //判断关注的状态，0未关注 1已关注 2相互关注 3已屏蔽
        if(Constants.STATUS_FOLLOW_EACH_OTHER.equals(mFollowStatus) || Constants.STATUS_ALREADY_FOLLOW.equals(mFollowStatus)) {//相互关注、已关注
            doUnFollow();
            return;
        }

        showLoadingDialog();

        //执行关注
        CommunityApiIO.getInstance().doCommunityFollow(mUserId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                //更关注列表
                EventBus.getDefault().post(new CommunityFollowEvent());
                setFollowStatus(Constants.STATUS_ALREADY_FOLLOW);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //取消关注
    private void doUnFollow() {
        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityFollowCancel(mUserId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                //更关注列表
                EventBus.getDefault().post(new CommunityFollowEvent());
                setFollowStatus(Constants.STATUS_UN_FOLLOW);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取查看用户社区动态数据
    private void getUserCommunityData() {
        if(StringUtils.isEmpty(mUserId)) {
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        CommunityApiIO.getInstance().getOtherUserCommunityInfo(mUserId, new APIRequestCallback<UserCommunityNewsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UserCommunityNewsJson res) {
                setData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void setData(UserCommunityNewsJson.UserCommunityNewsData data) {
        //头像
        GlideUtils.loadAvatar(mContext, iv_uc_avatar, data.getAvatar());
        //昵称
        mUserNickName = data.getUsername();
        nav_bar_user_community.setNavBarTitle(mUserNickName);
        //关注数量
        tv_uc_follows_value.setText(StringUtils.getNullEmptyConvertZero(data.getFocus_count()));
        //粉丝数量
        tv_uc_fans_value.setText(StringUtils.getNullEmptyConvertZero(data.getMy_focus_count()));
        //点赞数
        tv_uc_praise_value.setText(StringUtils.getNullEmptyConvertZero(data.getTotal_like()));
        //关注状态
        setFollowStatus(data.getFocus_status());

        //是否可以聊天 1可以 0不可以（对方将我拉黑，隐藏聊天图标）
        if(Constants.STATUS_GLOBAL_YES.equals(data.getEnable_chat())) {
            iv_uc_message.setVisibility(View.VISIBLE);
        } else {
            iv_uc_message.setVisibility(View.GONE);
        }
    }

    //关注状态 0未关注 1已关注 2相互关注 3已屏蔽（可以点击取消屏蔽）
    private void setFollowStatus(String status) {
        btn_uc_follow.setEnabled(true);

        mFollowStatus = status;

        if(Constants.STATUS_FOLLOW_EACH_OTHER.equals(mFollowStatus)) {
            btn_uc_follow.setText(R.string.text_follow_each_other);
        } else if(Constants.STATUS_ALREADY_FOLLOW.equals(mFollowStatus)) {
            btn_uc_follow.setText(R.string.text_follow_cancel);
        } else {
            btn_uc_follow.setText(R.string.text_follow);
        }
    }
}
